package ch8;

import java.util.*;

public class Example8_12  {
    public static void main(String args[]) {
        String shoppingReceipt = "牛奶:8.5圆,香蕉3.6圆，酱油:2.8圆";
        PriceToken lookPriceMess = new PriceToken();
        System.out.println(shoppingReceipt);
        double sum =lookPriceMess.getPriceSum(shoppingReceipt);
        System.out.printf("购物总价格%-7.2f",sum);
        int amount = lookPriceMess.getGoodsAmount(shoppingReceipt);
        double aver = lookPriceMess.getAverPrice(shoppingReceipt);
        System.out.printf("\n商品数目:%d,平均价格:%-7.2f",amount,aver);
    }
}

class PriceToken {
    public double getPriceSum(String shoppingReceipt) {
        String regex = "[^0123456789.]+"; //匹配非数字字符序列
        shoppingReceipt = shoppingReceipt.replaceAll(regex,"#");
        StringTokenizer fenxi = new StringTokenizer(shoppingReceipt,"#");
        double sum = 0;
        while(fenxi.hasMoreTokens()) {
            String item = fenxi.nextToken();
            double price = Double.parseDouble(item);
            sum = sum + price;
        }
        return sum;
    }
    public double getAverPrice(String shoppingReceipt){
        double priceSum = getPriceSum(shoppingReceipt);
        int goodsAmount = getGoodsAmount(shoppingReceipt);
        return priceSum/goodsAmount;
    }
    public int getGoodsAmount(String shoppingReceipt) {
        String regex = "[^0123456789.]+";
        shoppingReceipt = shoppingReceipt.replaceAll(regex,"#");
        StringTokenizer fenxi = new StringTokenizer(shoppingReceipt,"#");
        int amount = fenxi.countTokens();
        return amount;
    }
}